<template>
    <div class="switchs" :class="switchs == '1' ? 'on' : 'off'" @click="change()">
        <div></div>
    </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { handle, judge } from "@/utils/switch";
import { popMsg } from "@/utils/tools";
interface Props {
    modelValue?: any;
    data?: any;
    item?: any;
}
const props = withDefaults(defineProps<Props>(), {
    modelValue: "0",
    data: [],
    item: {},
});
const switchs = ref(props.modelValue);
const emit = defineEmits(["update:modelValue"]);
const change = () => {
    verify(() => {
        let item = JSON.parse(JSON.stringify(props.item));
        if (item.value == "1") {
            item.value = "0";
        } else {
            item.value = "1";
        }
        handle(item, (data: any) => {
            if (data) {
                if (switchs.value == "1") {
                    switchs.value = "0";
                } else {
                    switchs.value = "1";
                }
                emit("update:modelValue", switchs.value);
            }
        });
    });
};
const verify = (callback: Function) => {
    let item = JSON.parse(JSON.stringify(props.item));
    getValue((obj: any) => {
        if (item.name != "电源总闸" && item.value == "0") {
            if (obj.poe == "0") {
                popMsg.error("请先打开电源总闸！");
            } else {
                callback();
            }
        } else if (item.name == "电源总闸" && item.value == "1") {
            if (obj.rd.includes("1")) {
                popMsg.error("请先关闭其他开关！");
            } else {
                judge(() => {
                    item.value = "0";
                    switchs.value = "0";
                    emit("update:modelValue", switchs.value);
                });
            }
        } else {
            callback();
        }
    });
};
const getValue = (callback: Function) => {
    let data = props.data;
    let obj: any = {
        rd: [],
        poe: "0",
    };
    data.forEach((v: any) => {
        v.item.forEach((i: any) => {
            if (i.name != "电源总闸") {
                obj.rd.push(i.value);
            } else {
                obj.poe = i.value;
            }
        });
    });
    callback(obj);
};
</script>
<style scoped lang="scss">
.switchs {
    width: 0.39rem;
    height: 0.19rem;
    border-radius: 0.32rem;
    overflow: hidden;
    position: relative;
    transition: all 0.2s;
    cursor: pointer;
    div {
        width: 0.19rem;
        height: 0.19rem;
        border-radius: 100%;
        background: #ffffff;
        position: absolute;
        top: 0;
        bottom: 0;
        transition: all 0.2s;
    }
}
.on {
    background: #00d22e;
    div {
        left: 0.2rem;
    }
}
.off {
    background: #6e767d;
    div {
        left: 0;
    }
}
</style>
